package com.sky.service.impl;

import com.sky.constant.MessageConstant;
import com.sky.dto.GoodsSalesDTO;
import com.sky.entity.Orders;
import com.sky.exception.ReportErrorException;
import com.sky.mapper.OrderMapper;
import com.sky.mapper.UserMapper;
import com.sky.service.ReportService;
import com.sky.service.WorkspaceService;
import com.sky.vo.*;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class ReportServiceImpl implements ReportService {
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private WorkspaceService workspaceService;

    /**
     * 统计指定时间区间内的营业额数据
     *
     * @param begin 开始时间
     * @param end   结束时间
     * @return 统计数据
     */
    @Override
    public TurnoverReportVO getTurnoverStatistics(LocalDate begin, LocalDate end) {
        if (begin.isAfter(end)) throw new ReportErrorException(MessageConstant.REPORT_TIME_ERROR);
        // 用于存放从begin到end范围内的每天的日期
        List<LocalDate> dateList = new ArrayList<>();
        // 用于存放每天的营业额
        List<Double> turnoverList = new ArrayList<>();

        LocalDate date = begin;
        while (!date.isAfter(end)) {
            // 将日期放入集合中
            dateList.add(date);
            // 查询date日期对应的营业额数据：“已完成”订单的订单金额统计
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);
            Map<String, Object> map = new HashMap<>();
            map.put("begin", beginTime);
            map.put("end", endTime);
            map.put("status", Orders.COMPLETED);

            Double turnover = orderMapper.sumByMap(map);
            if (turnover == null) turnover = 0.0;
            turnoverList.add(turnover);
            // 日期往后一天
            date = date.plusDays(1);
        }
        return TurnoverReportVO.builder()
                .dateList(StringUtils.join(dateList, ","))
                .turnoverList(StringUtils.join(turnoverList, ","))
                .build();
    }

    /**
     * 统计指定时间区间内的用户数据
     *
     * @param begin 开始时间
     * @param end   结束时间
     * @return 统计结果
     */
    @Override
    public UserReportVO getUserStatistics(LocalDate begin, LocalDate end) {
        if (begin.isAfter(end)) throw new ReportErrorException(MessageConstant.REPORT_TIME_ERROR);
        // 用于存放从begin到end范围内的每天的日期
        List<LocalDate> dateList = new ArrayList<>();
        // 用于存放每天的用户总量
        List<Integer> totalUserList = new ArrayList<>();
        // 用于存放每天新增的用户
        List<Integer> newUserList = new ArrayList<>();

        LocalDate date = begin;
        while (!date.isAfter(end)) {
            // 将日期放入集合中
            dateList.add(date);

            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);
            Map<String, Object> map = new HashMap<>();
            map.put("end", endTime);
            // 查询date日期对应的用户总量数据
            Integer total = userMapper.countByMap(map);
            if (total == null) total = 0;
            totalUserList.add(total);

            // 查询date日期对应的新增用户量数据
            map.put("begin", beginTime);
            Integer newUsers = userMapper.countByMap(map);
            if (newUsers == null) newUsers = 0;
            newUserList.add(newUsers);
            // 日期往后一天
            date = date.plusDays(1);
        }
        return UserReportVO.builder()
                .dateList(StringUtils.join(dateList, ","))
                .totalUserList(StringUtils.join(totalUserList, ","))
                .newUserList(StringUtils.join(newUserList, ","))
                .build();
    }

    /**
     * 统计指定时间区间内的订单数据
     *
     * @param begin 开始时间
     * @param end   结束时间
     * @return 统计结果
     */
    @Override
    public OrderReportVO getOrdersStatistics(LocalDate begin, LocalDate end) {
        if (begin.isAfter(end)) throw new ReportErrorException(MessageConstant.REPORT_TIME_ERROR);
        // 用于存放从begin到end范围内的每天的日期
        List<LocalDate> dateList = new ArrayList<>();
        // 用于存放每日订单数
        List<Integer> orderCountList = new ArrayList<>();
        // 用于存放每日有效订单数
        List<Integer> validOrderCountList = new ArrayList<>();
        LocalDate date = begin;
        while (!date.isAfter(end)) {
            // 将日期放入集合中
            dateList.add(date);

            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);
            Map<String, Object> map = new HashMap<>();
            map.put("end", endTime);
            map.put("begin", beginTime);
            // 查询订单总数
            Integer orderCount = orderMapper.countByMap(map);
            if (orderCount == null) orderCount = 0;
            orderCountList.add(orderCount);
            // 查询有效订单数
            map.put("status", Orders.COMPLETED);
            Integer validOrderCount = orderMapper.countByMap(map);
            if (validOrderCount == null) validOrderCount = 0;
            validOrderCountList.add(validOrderCount);
            // 日期往后一天
            date = date.plusDays(1);
        }
        // 计算时间区间内的订单总数量
        Integer totalOrderCount = orderCountList.stream().reduce(Integer::sum).orElse(0);
        // 计算时间区间内的有效订单数量
        Integer validOrderCount = validOrderCountList.stream().reduce(Integer::sum).orElse(0);

        double orderCompletionRate = 0.0;
        // 计算订单完成率
        if (totalOrderCount != 0) {
            orderCompletionRate = validOrderCount.doubleValue() / totalOrderCount;
        }
        return OrderReportVO.builder()
                .dateList(StringUtils.join(dateList, ","))
                .orderCountList(StringUtils.join(orderCountList, ","))
                .validOrderCountList(StringUtils.join(validOrderCountList, ","))
                .totalOrderCount(totalOrderCount)
                .validOrderCount(validOrderCount)
                .orderCompletionRate(orderCompletionRate)
                .build();
    }

    /**
     * 统计指定时间区间内的销量排名Top10
     *
     * @param begin 开始时间
     * @param end   结束时间
     * @return 统计结果
     */
    @Override
    public SalesTop10ReportVO getTop10(LocalDate begin, LocalDate end) {
        if (begin.isAfter(end)) throw new ReportErrorException(MessageConstant.REPORT_TIME_ERROR);

        LocalDateTime beginTime = LocalDateTime.of(begin, LocalTime.MIN);
        LocalDateTime endTime = LocalDateTime.of(end, LocalTime.MAX);
        // 获取查询的封装对象
        List<GoodsSalesDTO> salesTop10 = orderMapper.getSalesTop10(beginTime, endTime);
        // 用于存放商品名称列表
        List<String> nameList = salesTop10.stream().map(GoodsSalesDTO::getName).collect(Collectors.toList());
        // 用于存放销量列表
        List<Integer> numberList = salesTop10.stream().map(GoodsSalesDTO::getNumbers).collect(Collectors.toList());
        // 封装返回结果数据
        return SalesTop10ReportVO.builder()
                .nameList(StringUtils.join(nameList, ","))
                .numberList(StringUtils.join(numberList, ","))
                .build();
    }

    /**
     * 导出运营数据报表
     *
     * @param response 响应
     */
    @Override
    public void exportBusinessData(HttpServletResponse response) {
        // 1.查询数据库，获取营业数据
        // 查询概览数据
        LocalDate begin = LocalDate.now().minusDays(30);
        LocalDate end = LocalDate.now().minusDays(1);
        BusinessDataVO businessData = workspaceService.getBusinessData(LocalDateTime.of(begin, LocalTime.MIN)
                , LocalDateTime.of(end, LocalTime.MAX));
        // 2.通过POI将数据写入Excel文件
        InputStream in = this.getClass().getClassLoader().getResourceAsStream("template/运营数据报表模板.xlsx");
        try {
            if (in == null) throw new IOException();
            // 基于模板文件创建一个新的Excel文件
            XSSFWorkbook excel = new XSSFWorkbook(in);
            // 获取表格文件的Sheet页
            XSSFSheet sheet = excel.getSheet("Sheet1");
            // 填充概览数据
            sheet.getRow(1).getCell(1).setCellValue("时间：" + begin + "至" + end);
            XSSFRow row = sheet.getRow(3);
            row.getCell(2).setCellValue(businessData.getTurnover());
            row.getCell(4).setCellValue(businessData.getOrderCompletionRate());
            row.getCell(6).setCellValue(businessData.getNewUsers());

            row = sheet.getRow(4);
            row.getCell(2).setCellValue(businessData.getValidOrderCount());
            row.getCell(4).setCellValue(businessData.getUnitPrice());
            // 填充明细数据
            for (int i = 0; i < 30; i++) {
                LocalDate date = begin.plusDays(i);
                // 查询某一天的营业数据
                businessData = workspaceService.getBusinessData(LocalDateTime.of(date, LocalTime.MIN)
                        , LocalDateTime.of(date, LocalTime.MAX));
                row = sheet.getRow(7 + i);
                row.getCell(1).setCellValue(date.toString());
                row.getCell(2).setCellValue(businessData.getTurnover());
                row.getCell(3).setCellValue(businessData.getValidOrderCount());
                row.getCell(4).setCellValue(businessData.getOrderCompletionRate());
                row.getCell(5).setCellValue(businessData.getUnitPrice());
                row.getCell(6).setCellValue(businessData.getNewUsers());
            }
            // 3.通过输出流将Excel文件下载到客户端浏览器
            ServletOutputStream outputStream = response.getOutputStream();
            excel.write(outputStream);
            // 关闭资源
            outputStream.close();
            excel.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
